package com.example.ht;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;

/**
 * 画图
 */
public class MainActivity extends Activity {
    private static final String TAG = "MainActivity";
    private Canvas canvas;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final ImageView iv_img = (ImageView) findViewById(R.id.iv_img);

        Bitmap srcBitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.bg);

        //创建副本
        final Bitmap copyBitmap = Bitmap.createBitmap(srcBitmap.getWidth(), srcBitmap.getHeight(), srcBitmap.getConfig());

        //画布
        canvas = new Canvas(copyBitmap);

        //画笔
        final Paint paint = new Paint();
        //颜色
        paint.setColor(Color.RED);
        //宽度
        paint.setStrokeWidth(15);


        //开始画画
        canvas.drawBitmap(srcBitmap,new Matrix(),paint);

        iv_img.setImageBitmap(srcBitmap);
        //设置Touch 事件
        iv_img.setOnTouchListener(new View.OnTouchListener() {

            int  startX = 0 ;
            int  startY = 0;

            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {

                int action = motionEvent.getAction();

                switch (action){

                    case MotionEvent.ACTION_DOWN: //按下
                        startX = (int) motionEvent.getX();
                        startY = (int) motionEvent.getY();
                        Log.i(TAG, "按下 : "+motionEvent.getX() +"-----"+motionEvent.getY());

                        break;
                    case MotionEvent.ACTION_MOVE : //移动
                        Log.i(TAG, "移动 : "+motionEvent.getX() +"-----"+motionEvent.getY());

                        //设置线条终点坐标
                        int stopX = (int) motionEvent.getX();
                        int stopY = (int) motionEvent.getY();

                        canvas.drawLine(startX,startY,stopX,stopY,paint);

                        startX = stopX;
                        startY = stopY;

                        //设置图片
                        iv_img.setImageBitmap(copyBitmap);
                        break;

                    case MotionEvent.ACTION_UP: //抬起
                        Log.i(TAG, "抬起 : "+motionEvent.getX() +"-----"+motionEvent.getY());
                        break;


                }
                return true;
            }
        });
    }
}
